/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.home.fragment;

import static com.dataoke.shoppingguide.app773026.bean.Constants.ALL_ITEM_LIST_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.PRODUCT_ID_KEY;
import static com.dataoke.shoppingguide.app773026.bean.Constants.PRODUCT_LIST_URL;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.RequestManager;
import com.dataoke.shoppingguide.app773026.activity.detail.ProductDetailActivity;
import com.dataoke.shoppingguide.app773026.adapter.ProductListAdapter;
import com.dataoke.shoppingguide.app773026.bean.AllItemResBean;
import com.dataoke.shoppingguide.app773026.bean.ProductItemBean;
import com.dataoke.shoppingguide.app773026.bean.ProductListBean;
import com.dataoke.shoppingguide.app773026.bean.CategoryBean;
import com.dataoke.shoppingguide.app773026.util.HttpTools;

import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.base.fragments.BaseFragment;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class HaodankuListFragment extends BaseFragment
        implements
        ProductListAdapter.OnItemClickListener,
        OnRefreshLoadMoreListener {
    protected SmartRefreshLayout mRefreshLayout;
    protected ProductListAdapter mProductListAdapter;
    private int page = 1;
    private boolean replace = false;

    protected RequestManager mImgLoader;

    private CategoryBean categoryBean;

    protected static final String KEY_CATE = "category";
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_main;
    }
    public static HaodankuListFragment newInstance(CategoryBean categoryBean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_CATE, categoryBean);
        HaodankuListFragment haodankuListFragment = new HaodankuListFragment();
        haodankuListFragment.setArguments(bundle);
        return haodankuListFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.categoryBean = (CategoryBean) getArguments().getSerializable(KEY_CATE);
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mProductListAdapter = new ProductListAdapter(this);
        RecyclerView recycler = root.findViewById(R.id.recycler);
        mRefreshLayout = mRoot.findViewById(R.id.refreshLayout);
        mRefreshLayout.setEnableFooterFollowWhenNoMoreData(true);

        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        recycler.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        recycler.setAdapter(mProductListAdapter);
        mProductListAdapter.setOnItemClickListener(this);

        //recycler添加和删除动画
        recycler.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    protected void initData() {
        if("-1".equals(categoryBean.getCateId())) {
            HttpTools.get(String.format(PRODUCT_LIST_URL, page), new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e("HaodankuListFragment", String.format(PRODUCT_LIST_URL, page) + e.getMessage());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    try {
                        ProductListBean productListBean = JSON.parseObject(response.body().string(), ProductListBean.class);
                        if(productListBean.getCode() == 200) {
                            refreshData(productListBean.getData().getListItem().getList());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            String url = String.format(ALL_ITEM_LIST_URL, page) + "&category_id=" + categoryBean.getCateId();
            HttpTools.get(url, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e("HaodankuListFragment", String.format(ALL_ITEM_LIST_URL, categoryBean.getCateId(), page) + e.getMessage());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    try {
                        AllItemResBean productListBean = JSON.parseObject(response.body().string(), AllItemResBean.class);
                        if(productListBean.getCode() == 200) {
                            refreshData(productListBean.getData().getItems());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    protected void refreshData(List<ProductItemBean> items) {
        getActivity().runOnUiThread(() -> {
            if(replace) {
                mProductListAdapter.setData(items);
            } else {
                mProductListAdapter.addData(items);
            }

            replace = false;
        });
    }

    @Override
    public void onItemClick(int position, ProductItemBean itemBean) {
        Intent intent = new Intent(getContext(), ProductDetailActivity.class);
        intent.putExtra(PRODUCT_ID_KEY, itemBean.getId());
        getContext().startActivity(intent);
//        Toast.makeText(getContext(), itemBean.getItemShotTitle(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        initData();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        refreshLayout.getLayout().postDelayed(() -> {
            replace = true;
            page = 1;
            initData();
            refreshLayout.finishRefresh();
            refreshLayout.resetNoMoreData();//setNoMoreData(false);//恢复上拉状态
        }, 1500);
    }
}
